<template>
  <div class="app-container">
    <div class="positionName">
      <div class="positionFlag" /><span>{{positionName}} - 相似岗位平均薪资</span>
    </div>
    <el-row class="search-container">
      <!-- <el-form ref="form" :model="form" label-width="auto" inline>
        <el-form-item label="统计日期">
          <el-date-picker v-model="selectBetweenTime" size="small" type="monthrange" align="right" unlink-panels
            value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始月份" end-placeholder="结束月份"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="工作经验">
          <workYearSearch ref="regionRef" @change="onWorkYearChange" />
        </el-form-item>
        <el-form-item label="区域名称">
          <regoinSearch ref="regionRef" @onRegionChange="onRegionChange" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData()">查询</el-button>
          <el-popover placement="top-start" width="200" trigger="hover" content="通过您的筛选条件，计算平均薪酬以及职位总数">
            <el-button slot="reference" type="primary" @click="fetchTotalData()" style="margin-left:10px">计算查询结果
            </el-button>
          </el-popover>
        </el-form-item>
      </el-form> -->
    </el-row>
    <div class="list">
      <el-tooltip effect="light" placement="top">
        <div class="toolTipGuide" slot="content">
          <div class="toolTipTitle"></div>
          <div class="toolTipItems" v-for="item,index in stepInfo" :key="index">
            <div class="stepImageContainer"> <img :src="item.stepImage" class="stepImage"></div>
            <div class="stepDesc">{{item.stepDesc}}</div>
          </div>
        </div>
        <el-tooltip effect="light" placement="top">
          <div class="toolTipGuide" slot="content">
            <div class="toolTipTitle"></div>
            <div class="toolTipItems" v-for="item,index in stepInfo" :key="index">
              <div class="stepImageContainer"> <img :src="item.stepImage" class="stepImage"></div>
              <div class="stepDesc">{{item.stepDesc}}</div>
            </div>
          </div>
          <el-button size="mini" class="filter-item" icon="el-icon-download" @click="onExportClick">导出
          </el-button>
        </el-tooltip>
      </el-tooltip>
      <el-button size="mini" class="filter-item" @click="onAiStatClick" v-if="false">AI生成数据
      </el-button>
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row
        @sort-change='sortChange'>
        <el-table-column label="相似职位名称">
          <template slot-scope="scope">
            {{ scope.row.similarPositionName }}
          </template>
        </el-table-column>
        <el-table-column label="平均薪资">
          <template slot-scope="scope">
            {{ scope.row.similarPositionSalary }}
          </template>
        </el-table-column>

      </el-table>
    </div>
    <div class="pagination">
      <!-- <el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="tablePage.pageNum"
        :page-size="tablePage.pageSize" :page-sizes="pageSizes" :total="tablePage.total" @size-change="handleSizeChange"
        @current-change="handlePageChange" /> -->
    </div>
    <websocket ref="child" @initMessageBack="initMessageBack" />

    <div class="onAiStatContainer">
      <div v-html="aiStatContent" class="aiStatContent"></div>
    </div>
  </div>
</template>

<script>
import Websocket from "@/components/Websocket";
import {
  getSimilarJobSalaryList,
  getWorkSalaryTotalData,
  getSimilarJobSalaryListExport,
} from "@/api/salary";
import { operateSave } from "@/api/data";
import SelectRegion from "@/components/SelectRegion";

import regoinSearch from "@/views/position/components/regoinSearch";
import workYearSearch from "@/views/position/components/workYearSearch";

export default {
  name: "WorkSalary",
  components: { SelectRegion, regoinSearch, workYearSearch, Websocket },
  data() {
    return {
      form: {},
      list: null,
      totalData: {
        salaryNum: null,
        companyNum: null,
      },
      listLoading: true,
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 20, // 每页多少条
        total: 0, // 总记录数
      },
      positionName: "",
      selectTime: "",
      regionId: "",
      regionList: [],
      currentRegionName: "",
      pageSizes: [10, 20, 30],
      workYearOptions: [
        { value: "", label: "全部" },
        { value: "10", label: "不限" },
        { value: "20", label: "0-1年" },
        { value: "30", label: "1-3年" },
        { value: "40", label: "3-5年" },
        { value: "50", label: "5-10年" },
        { value: "60", label: "10年+" },
      ],
      workYearValue: "",

      orderByColumn: "",
      orderBy: "",

      selectBetweenTime: "",
      // 时间选择器
      pickerOptions: {
        shortcuts: [
          {
            text: "今年至今",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },

      aiCreateStatus: false,
      aiStatContent: "",
      messages: [],
      stepInfo: [
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide1.png",
          stepDesc: "第一步，打开导出文件",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide2.png",
          stepDesc: "第二步，选择数据范围。",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide3.png",
          stepDesc: "第三步，选择全部图表",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide4.png",
          stepDesc: "第四步，选择自己需要的样式备份",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide5.png",
          stepDesc: "第五步，图表制作完成啦！",
        },
      ],
    };
  },
  created() {
    this.positionName = this.$route.query.name;
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    onAiStatClick() {
      this.aiCreate(
        `根据中国国内主要招聘平台的数据统计，生成近2年来${this.positionName}的相似岗位平均薪酬，按以下格式返回结果： 
- 岗位1 xxxxx元/月 
- 岗位2 xxxxx元/月 
- 岗位3 xxxxx元/月 
- 岗位4 xxxxx元/月 
- 岗位5 xxxxx元/月 
- 岗位6 xxxxx元/月 
- 岗位7 xxxxx元/月 
- 岗位8 xxxxx元/月 ,如果没有数据，请你根据事实编造一些合理的数据。`
      );
    },
    aiCreate(questionContent) {
      if (this.aiCreateStatus) {
        this.$message({
          type: "warning",
          message:
            "已有AI正在生成中，等待生成内容结束或F5刷新页面再次点击AI生成!",
        });
        return;
      } else {
        this.aiStatContent = "";
        this.aiCreateStatus = true;
      }
      const name =
        this.$route.query.name != undefined ? this.$route.query.name : "";
      this.chatKey = questionContent.replace(/{}/g, name);

      this.messages.push({
        role: "user",
        content: this.chatKey,
      });
      // console.log('AI')
      const agentData = {
        userId: "",
        userName: "",
        messages: this.messages,
      };
      this.messages = [];
      this.sendMsg = JSON.stringify(agentData);
      this.$refs.child.send(this.sendMsg, this.initMessageBack, this.wsError);
      operateSave({
        ylPositionId: this.positionId,
        description: `AI生成-相似岗位平均薪资`,
      });
      this.$message.success({
        message: "AI生成内容中...",
        offset: "400",
      });
    },
    initMessageBack(res) {
      this.loading = true;
      if (res === "err") {
        this.loading = false;
        return (this.showError = true);
      }
      const msg = res.choices && res.choices[0];
      if (!this.currentRole) {
        this.currentRole = msg.delta.role;
      }
      if (msg.delta.role === "assistant") {
        return;
      }
      if (msg.finish_reason === "stop" || msg.finish_reason === "done") {
        this.loading = false;
        this.currentMsg = "";
        this.currentRole = "";
        this.aiCreateStatus = false;
        return;
      }
      var tempStr = msg.delta.content;
      if (tempStr) {
        tempStr = tempStr.replace(/(\r\n|\n|\r)+/g, "<br>");
      }
      this.aiStatContent += tempStr;
    },
    handleDateChange(val) {
      this.tablePage.pageNum = 1;
      this.fetchData();
    },
    onWorkYearChange(val) {
      this.workYearValue = val.value;
      this.tablePage.pageNum = 1;
      this.fetchData();
    },
    onRegionChange(val) {
      this.currentRegionName = val.label;
      this.tablePage.pageNum = 1;
      this.fetchData();
    },
    fetchData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
        page: this.tablePage.pageNum,
        perPage: this.tablePage.pageSize,
      };
      if (this.selectTime != "") {
        params.selectTime = this.selectTime;
      }
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.workYearValue != "") {
        params.selectValue = this.workYearValue;
      }

      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }

      if (this.orderByColumn != "" && this.orderBy != "") {
        params.orderByColumn = this.orderByColumn;
        params.orderBy = this.orderBy == "ascending" ? "asc" : "desc";
      } else {
        params.orderByColumn = "generate_time";
        params.orderBy = "desc";
      }

      getSimilarJobSalaryList(params).then((response) => {
        const count = response.data.count - 0;
        this.tablePage.total = count;
        this.list = response.data;
        this.listLoading = false;
      });
    },
    fetchTotalData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
      };
      if (this.workYearValue != "") {
        params.selectValue = this.workYearValue;
      }
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }
      this.fetchData();
      getWorkSalaryTotalData(params).then((response) => {
        if (
          response.data != null &&
          response.data.companyNum != null &&
          response.data.salaryNum != null
        ) {
          this.totalData.salaryNum = parseFloat(
            response.data.salaryNum
          ).toFixed(2);
          this.totalData.companyNum = response.data.companyNum;
        } else {
          this.totalData.salaryNum = 0;
          this.totalData.companyNum = 0;
        }
        let content =
          `<div style='border-top:1px solid #e8e8e8;border-bottom:1px solid #e8e8e8;margin-top:-10px;font-size:14px;padding:28px 0;text-align:left;'>` +
          "<div style='font-size:16px;font-weight:bold;color:#222;margin-bottom:0px;'>通过您的查询条件（岗位，地区，时间）可得：</div>" +
          "<br/>" +
          "您查询的地区：[ " +
          (this.currentRegionName == "" || this.currentRegionName == null
            ? "全国"
            : this.currentRegionName) +
          " ] " +
          "<br>" +
          " 您查询的时间区间为：[ " +
          (this.selectBetweenTime == "" || this.selectBetweenTime == null
            ? "不限时间"
            : this.selectBetweenTime) +
          " ] " +
          "<br>" +
          "  平均薪酬为： " +
          this.totalData.salaryNum +
          "<br>" +
          " 职位总数为： " +
          this.totalData.companyNum;
        +`</div>`;

        this.$alert(content, "计算查询结果", {
          confirmButtonText: "确定",
          dangerouslyUseHTMLString: true,
        });
        this.listLoading = false;
      });
    },
    handlePageChange(currentPage) {
      this.tablePage.pageNum = currentPage;
      this.fetchData();
      // 在此刷新数据
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize;
      this.fetchData();
      // 在此刷新数据
    },
    onExportClick() {
      // 导出方法
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
        page: 1,
        perPage: 10000,
      };
      if (this.selectTime != "") {
        params.selectTime = this.selectTime;
      }
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.workYearValue != "") {
        params.selectValue = this.workYearValue;
      }
      if (this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }

      if (this.orderByColumn != "" && this.orderBy != "") {
        params.orderByColumn = this.orderByColumn;
        params.orderBy = this.orderBy == "ascending" ? "asc" : "desc";
      } else {
        params.orderByColumn = "generate_time";
        params.orderBy = "desc";
      }

      getSimilarJobSalaryListExport(params)
        .then((result) => {
          const link = document.createElement("a"); // 创建a标签
          const blob = new Blob([result], { type: "application/vnd.ms-excel" }); // 设置文件流
          link.style.display = "none";
          // 设置连接
          link.href = URL.createObjectURL(blob); // 将文件流转化为blob地址
          link.download =
            (this.$route.query.name != undefined
              ? this.$route.query.name
              : "") + "工作经验薪酬数据统计表";
          document.body.appendChild(link);
          // 模拟点击事件
          link.click(); // 设置点击事件
          this.listLoading = false;
          window.URL.revokeObjectURL(link.href); // 释放掉blob对象
          document.body.removeChild(link); // 下载完成移除元素
        })
        .catch((err) => {
          console.log(err);
        });
    },
    sortChange(column) {
      this.orderByColumn = column.prop != null ? column.prop : "generate_time";
      this.orderBy = column.order != null ? column.order : "desc";
      this.fetchData();
      // 在此刷新数据
    },
  },
};
</script>

<style scoped>
.positionName {
  display: flex;
  width: 100vw;
  align-items: center;
  color: #333333;
  background-color: #edf6ff;
  height: 48px;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 12px;
  margin-left: -56px;
  padding: 0 55px;
}
.list {
  /* height: 650px;
  overflow-y: auto; */
}
.app-container {
  padding-right: 56px;
  padding-top: 0;
  min-height: 720px;
}
.search-container {
  /* margin-bottom: 24px; */
}
.pagination {
  margin-top: 24px;
}
::v-deep .el-table th > .cell {
  color: rgba(0, 0, 0, 0.85);
}
::v-deep .el-table th {
  background-color: #fafafa;
}
::v-deep.el-form--inline .el-form-item {
  margin-right: 24px;
}
.filter-item {
  margin-bottom: 12px;
}
::v-deep .el-form-item {
  display: flex;
  align-items: center;
}
::v-deep .el-form-item__label {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 27px;
  min-width: 68px !important;
}
::v-deep .el-form-item__content {
  margin-left: 0 !important;
}

.onAiStatContainer {
  margin-top: 20px;
}
.aiStatContent {
  font-size: 14px;
  color: rgb(96, 98, 102);
  max-width: 60%;
  line-height: 28px;
  color: #1677db;
  margin-top: 28px;
  word-break: break-all;
  white-space: normal;
}
.toolTipGuide {
  display: flex;
}
.toolTipItems {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.stepImageContainer {
}
.stepImage {
  width: 264px;
  height: 149px;
}
.stepDesc {
  margin-top: 14px;
  font-size: 14px;
}
</style>
